<?php

namespace App\Models;

use Illuminate\Support\Facades\DB;

class Article extends blog
{
    const PUBLISH_STATE = [
            'on'  => ['value' => 1, 'text' => '是', 'color' => 'success'],
            'off' => ['value' => 0, 'text' => '否', 'color' => 'danger'],
        ];

    /**
     * 已发布的文章
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopePublish($query)
    {
        return $query->where('is_publish', 1);
    }
    
    public function category()
    {
        return $this->belongsTo(Category::class, 'cid', 'id');
    }

    public static function getNextArticle($id)
    {
        $nextId = self::publish()->where('id', '>', $id)->min('id');
        return empty($nextId) ? false : self::publish()->select('id', 'url', 'title')->find($nextId);
    }

    public static function getPreviousArticle($id)
    {
        $previousId = self::publish()->where('id', '<', $id)->max('id');
        return empty($previousId) ? false : self::publish()->select('id', 'url', 'title')->find($previousId);
    }

    public static function getArticleByYear()
    {
        $year = self::publish()->selectRaw("DATE_FORMAt(created_at,'%Y') as y")->orderBy('y', 'desc')->groupBy('y')->pluck('y');
        $data = [];
        if (!empty($year)) {
            foreach($year as $y) {
                $data[$y] = self::publish()->where(DB::Raw("DATE_FORMAt(created_at,'%Y')"), $y)
                    ->orderBy('created_at', 'desc')
                    ->get(['id','title','url',DB::Raw("DATE_FORMAt(created_at,'%m/%d') as dateline")]);
            }
        }
        return $data;
    }

    public function link($params = [])
    {
        return route('article.show', array_merge([$this->id], $params));
    }
}
